package com.yellowpage.white.util;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;


/**
 * HTTP工具类.
 * 
 * @author David.Huang
 */
public class HttpUtil {

	
	/** 默认编码方式 -UTF8 */
	private static final String DEFAULT_ENCODE = "utf-8";
	
	/**
	 * 构造方法
	 */
	public HttpUtil() {
		
	}
	
	public static CloseableHttpClient getHttpClient(){
		HttpRoutePlanner routePlanner = new HttpRoutePlanner() {

		    public HttpRoute determineRoute(
		            HttpHost target,
		            HttpRequest request,
		            HttpContext context) throws HttpException {
		        return new HttpRoute(target, null,  new HttpHost("192.168.19.9", 80),
		                "https".equalsIgnoreCase(target.getSchemeName()));
		    }

		};
		CloseableHttpClient client = HttpClients.custom()
		        .setRoutePlanner(routePlanner)
		        .build();
		
		
		
		return client;
	}

	/**
	 * GET请求, 结果以字符串形式返回.
	 * 
	 * @param url
	 *            请求地址
	 * @return 内容字符串
	 */
	public static String getUrlAsString(String url) throws Exception {
		return getUrlAsString(url, new HashMap(), DEFAULT_ENCODE);
	}

	/**
	 * GET请求, 结果以字符串形式返回.
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @return 内容字符串
	 */
	public static String getUrlAsString(String url, Map<String, String> params)
			throws Exception {
		return getUrlAsString(url, params, DEFAULT_ENCODE);
	}

	/**
	 * GET请求, 结果以字符串形式返回.
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @param encode
	 *            编码方式
	 * @return 内容字符串
	 */
	public static String getUrlAsString(String url, Map<String, String> params,
			String encode) throws Exception {
		// 开始时间
		long t1 = System.currentTimeMillis();
		// 获得HttpGet对象
		HttpGet httpGet = getHttpGet(url, params, encode);
		
		
		// 发送请求
		String result = executeHttpRequest(httpGet, null);
		// 结束时间
		long t2 = System.currentTimeMillis();
		// 调试信息
		
		// 返回结果
		return result;
	}

	/**
	 * POST请求, 结果以字符串形式返回.
	 * 
	 * @param url
	 *            请求地址
	 * @return 内容字符串
	 */
	public static String postUrlAsString(String url) throws Exception {
		return postUrlAsString(url, null, null, null);
	}

	/**
	 * POST请求, 结果以字符串形式返回.
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @return 内容字符串
	 */
	public static String postUrlAsString(String url, Map<String, String> params)
			throws Exception {
		return postUrlAsString(url, params, null, null);
	}

	/**
	 * POST请求, 结果以字符串形式返回.
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @param reqHeader
	 *            请求头内容
	 * @return 内容字符串
	 * @throws Exception
	 */
	public static String postUrlAsString(String url,
			Map<String, String> params, Map<String, String> reqHeader)
			throws Exception {
		return postUrlAsString(url, params, reqHeader, null);
	}

	/**
	 * POST请求, 结果以字符串形式返回.
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @param reqHeader
	 *            请求头内容
	 * @param encode
	 *            编码方式
	 * @return 内容字符串
	 * @throws Exception
	 */
	public static String postUrlAsString(String url,
			Map<String, String> params, Map<String, String> reqHeader,
			String encode) throws Exception {
		// 开始时间
		long t1 = System.currentTimeMillis();
		// 获得HttpPost对象
		HttpPost httpPost = getHttpPost(url, params, encode);
		// 发送请求
		String result = executeHttpRequest(httpPost, reqHeader);
		// 结束时间
		long t2 = System.currentTimeMillis();
		
		
		// 返回结果
		return result;
	}

	/**
	 * 获得HttpGet对象
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @param encode
	 *            编码方式
	 * @return HttpGet对象
	 */
	private static HttpGet getHttpGet(String url, Map<String, String> params,
			String encode) {
		StringBuffer buf = new StringBuffer(url);
		if (params != null) {
			// 地址增加?或者&
			String flag = (url.indexOf('?') == -1) ? "?" : "&";
			// 添加参数
			for (String name : params.keySet()) {
				buf.append(flag);
				buf.append(name);
				buf.append("=");
				try {
					String param = params.get(name);
					if (param == null) {
						param = "";
					}
					buf.append(URLEncoder.encode(param, encode));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				flag = "&";
			}
		}
		HttpGet httpGet = new HttpGet(buf.toString());
		return httpGet;
	}

	/**
	 * 获得HttpPost对象
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @param encode
	 *            编码方式
	 * @return HttpPost对象
	 */
	private static HttpPost getHttpPost(String url, Map<String, String> params,
			String encode) {
		HttpPost httpPost = new HttpPost(url);
		if (params != null) {
			List<NameValuePair> form = new ArrayList<NameValuePair>();
			for (String name : params.keySet()) {
				form.add(new BasicNameValuePair(name, params.get(name)));
			}
			try {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form,
						encode);
				httpPost.setEntity(entity);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return httpPost;
	}

	/**
	 * 执行HTTP请求
	 * 
	 * @param request
	 *            请求对象
	 * @param reqHeader
	 *            请求头信息
	 * @return 内容字符串
	 */
	private static String executeHttpRequest(HttpUriRequest request,
			Map<String, String> reqHeader) throws Exception {
		HttpClient client = null;
		String result = null;
		try {
			// 创建HttpClient对象			
			client = getHttpClient();
			
			
			// 设置请求头信息
			if (reqHeader != null) {
				for (String name : reqHeader.keySet()) {
					request.addHeader(name, reqHeader.get(name));
				}
			}
			// 获得返回结果
			HttpResponse response = client.execute(request);
			
			
			
			// 如果成功
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//result = response.getEntity().toString(); // EntityUtils.toString(response.getEntity());
				//EntityUtils.toString(response.getEntity(), "ja");
				
				byte[] content = new byte[20480];
				response.getEntity().getContent().read(content);
				//Shift_JIS、EUC-JP、ISO-2022-JP
				result = new String(content, "Shift_JIS");
				
				
			}
			// 如果失败
			else {
				StringBuffer errorMsg = new StringBuffer();
				errorMsg.append("httpStatus:");
				errorMsg.append(response.getStatusLine().getStatusCode());
				errorMsg.append(response.getStatusLine().getReasonPhrase());
				errorMsg.append(", Header: ");
				Header[] headers = response.getAllHeaders();
				for (Header header : headers) {
					errorMsg.append(header.getName());
					errorMsg.append(":");
					errorMsg.append(header.getValue());
				}
				
			}
		} catch (Exception e) {
			
			
			e.printStackTrace();
			throw new Exception("http连接异常");
			
		} finally {
			try {
				client.getConnectionManager().shutdown();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 下载文件保存到本地
	 * 
	 * @param path
	 *            文件保存位置
	 * @param url
	 *            文件地址
	 * @throws IOException
	 */
	public static void downloadFile(String path, String url) throws IOException {
		
		HttpRoutePlanner routePlanner = new HttpRoutePlanner() {

		    public HttpRoute determineRoute(
		            HttpHost target,
		            HttpRequest request,
		            HttpContext context) throws HttpException {
		        return new HttpRoute(target, null,  new HttpHost("192.168.19.9", 80),
		                "https".equalsIgnoreCase(target.getSchemeName()));
		    }

		};
		CloseableHttpClient client = HttpClients.custom()
		        .setRoutePlanner(routePlanner)
		        .build();
		
		
		try {
			// 创建HttpClient对象
			//client = new DefaultHttpClient();
			// 获得HttpGet对象
			HttpGet httpGet = getHttpGet(url, null, null);
			// 发送请求获得返回结果
			HttpResponse response = client.execute(httpGet);
			// 如果成功
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				byte[] result = EntityUtils.toByteArray(response.getEntity());
				BufferedOutputStream bw = null;
				try {
					// 创建文件对象
					File f = new File(path);
					// 创建文件路径
					if (!f.getParentFile().exists())
						f.getParentFile().mkdirs();
					// 写入文件
					bw = new BufferedOutputStream(new FileOutputStream(path));
					bw.write(result);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (bw != null)
							bw.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			// 如果失败
			else {
				StringBuffer errorMsg = new StringBuffer();
				errorMsg.append("httpStatus:");
				errorMsg.append(response.getStatusLine().getStatusCode());
				errorMsg.append(response.getStatusLine().getReasonPhrase());
				errorMsg.append(", Header: ");
				Header[] headers = response.getAllHeaders();
				for (Header header : headers) {
					errorMsg.append(header.getName());
					errorMsg.append(":");
					errorMsg.append(header.getValue());
				}
				
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				client.getConnectionManager().shutdown();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void getHttpFile2(String path, String url ){
		
		HttpRoutePlanner routePlanner = new HttpRoutePlanner() {

		    public HttpRoute determineRoute(
		            HttpHost target,
		            HttpRequest request,
		            HttpContext context) throws HttpException {
		        return new HttpRoute(target, null,  new HttpHost("someproxy", 80),
		                "https".equalsIgnoreCase(target.getSchemeName()));
		    }

		};
		CloseableHttpClient httpclient = HttpClients.custom()
		        .setRoutePlanner(routePlanner)
		        .build();
		
		
		//CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpget = new HttpGet(url);
		CloseableHttpResponse response = null;
		
		BufferedOutputStream bw = null;
		
		try {
			response = httpclient.execute(httpget);
			
		    HttpEntity entity = response.getEntity();
		    if (entity != null) {
		        InputStream instream = entity.getContent();
		        int byteOne = instream.read();
		        int byteTwo = instream.read();
		        // Do not need the rest
		    }
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			try{
				response.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		    
		}
	}

	public static void main(String[] args){
			
		//HttpUtil hu = new HttpUtil();
		try{
			//hu.downloadFile("C:\\PROJECTS\\UBSS\\114黄页\\03_系统测试\\TEMP\\2014-12-26-13.zip", "http://101.227.246.1/2014-12-26-13.zip");
			
			// 90001-91000
			//91001-92000
			// 92001-93000/98001-99000
			// 2401-2500/8401-8500 
			//91001-92000  1001-2000 2001-2020  
			//2101-2200 9101-9200 2201-2300
			//2301-2400/2901-3000/8301-8400/8901-9000/9301-9400
			//2401-2500/8401-8500
			for(int i = 91001; i <= 92000; i++){
				System.out.println(i);
				HttpUtil.downloadFile("C:\\PROJECTS\\UBSS\\114黄页\\03_系统测试\\TEMP\\" + i + ".jpg",
				"http://www.tomytec.co.jp/tomix/products/n/images/" + i + ".jpg");
			}
			
			//http://www.tomytec.co.jp/tomix/products/n/images/ 
			
			
			/**
			for(int i = 92101; i < 93000; i++){
				HttpUtil.downloadFile("C:\\PROJECTS\\UBSS\\114黄页\\03_系统测试\\TEMP\\" + i + "_hl.gif",
				"http://www.tomytec.co.jp/tomix/products/n/images/" + i + "_hl.gif");
			}**/
			
			
			//String result = HttpUtil.getUrlAsString("http://bbs.78dm.net/forum.php?mod=viewthread&tid=356333");
			//String result = HttpUtil.getUrlAsString("http://www.tomytec.co.jp/tomix/products/n/92196.htm");
			
			
			//System.out.println(result);
			
		
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

